<template>
  <div class="user-management">
    <!-- 搜索表单 -->
    <BaseForm
      ref="searchFormRef"
      v-model:formData="searchFormData"
      :form-list="searchFormList"
      :inline="true"
      label-position="right"
      class="search-form"
    >
      <template #button>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="success" @click="handleAdd">新增</el-button>
      </template>
    </BaseForm>

    <!-- 用户表格 -->
    <CommonTable :tableData="tableData" :columns="tableColumns" :loading="loading" border>
      <template #status="{ row }">
        <el-tag :type="row.status === '0' ? 'success' : 'danger'">
          {{ row.status === "0" ? "启用" : "禁用" }}
        </el-tag>
      </template>
      <!-- 新增角色标签展示插槽 -->
      <template #roles="{ row }">
        <div class="role-tags">
          <template v-if="row.roles && row.roles.length > 0">
            <el-tag
              v-for="role in row.roles"
              :key="role.id"
              type="primary"
              style="margin-right: 5px; margin-bottom: 5px"
            >
              {{ role.roleName }}
            </el-tag>
          </template>
          <template v-else>
            <span>-</span>
          </template>
        </div>
      </template>
      <template #opt="{ row }">
        <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
        <el-button size="small" type="warning" @click="handleAssignRoles(row)">分配角色</el-button>
        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
      </template>
    </CommonTable>

    <!-- 分页 -->
    <Pagination
      v-model="pagination"
      @update:modelValue="handlePageChange"
      :page-sizes="[10, 20, 50, 100]"
    />

    <!-- 用户编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <BaseForm
        ref="userFormRef"
        v-model:formData="userFormData"
        :form-list="userFormList"
        :rules="userFormRules"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" v-model="roleDialogVisible" width="600px">
      <el-tree
        ref="roleTreeRef"
        :data="roleList"
        show-checkbox
        node-key="id"
        :props="roleProps"
        :default-checked-keys="selectedRoleIds"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveRoles">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import BaseForm from "@/components/Form/BaseForm.vue";
import CommonTable from "@/components/Table/CommonTable.vue";
import Pagination from "@/components/Pagination/Pagination.vue";
import userApi from "@/api/system/user";
import roleApi from "@/api/system/role";

// 搜索表单引用
const searchFormRef = ref<InstanceType<typeof BaseForm> | null>(null);
// 用户表单引用
const userFormRef = ref<InstanceType<typeof BaseForm> | null>(null);
// 角色树引用
const roleTreeRef = ref();

// 搜索表单数据
const searchFormData = reactive({
  userName: "",
  nickName: "",
  phone: "",
});

// 搜索表单配置
const searchFormList = [
  {
    key: "userName",
    tag: "el-input",
    label: "用户名",
    props: {
      placeholder: "请输入用户名",
      clearable: true,
    },
  },
  {
    key: "nickName",
    tag: "el-input",
    label: "昵称",
    props: {
      placeholder: "请输入昵称",
      clearable: true,
    },
  },
  {
    key: "phone",
    tag: "el-input",
    label: "手机号",
    props: {
      placeholder: "请输入手机号",
      clearable: true,
    },
  },
];

// 表格列配置
const tableColumns = [
  {
    label: "用户名",
    prop: "userName",
  },
  {
    label: "昵称",
    prop: "nickName",
  },
  // 删除性别列
  {
    label: "手机号",
    prop: "phone",
  },
  {
    label: "邮箱",
    prop: "email",
  },
  // 新增角色列
  {
    label: "角色",
    prop: "roles",
  },
  {
    label: "状态",
    prop: "status",
  },
  {
    label: "创建时间",
    prop: "createTime",
    width: 180,
  },
  {
    label: "操作",
    width: 300,
    props: {
      fixed: "right",
    },
  },
];

// 表格数据
const tableData = ref([]);
// 加载状态
const loading = ref(false);
// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0,
});

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const isEdit = ref(false);

// 分配角色对话框
const roleDialogVisible = ref(false);
const currentUserId = ref<number | null>(null);
const selectedRoleIds = ref<number[]>([]);
const roleList = ref([]);

// 角色树属性
const roleProps = {
  label: "roleName",
  children: "children",
};

// 用户表单数据 (删除sex和avatar字段)
const userFormData = reactive({
  id: undefined,
  deptId: undefined,
  userName: "",
  nickName: "",
  userType: "00",
  email: "",
  phone: "",
  // 删除sex字段
  // 删除avatar字段
  password: "",
  status: "1",
  loginIp: "",
  loginDate: "",
});

// 用户表单配置 (删除sex和avatar配置)
const userFormList: any = [
  {
    key: "userName",
    tag: "el-input",
    label: "用户名",
    required: true,
    props: {
      placeholder: "请输入用户名",
    },
  },
  {
    key: "password",
    tag: "el-input",
    label: "密码",
    required: true,
    props: {
      placeholder: "请输入密码",
      type: "password",
      showPassword: true,
    },
    show: () => !isEdit.value,
  },
  {
    key: "nickName",
    tag: "el-input",
    label: "昵称",
    required: true,
    props: {
      placeholder: "请输入昵称",
    },
  },
  {
    key: "email",
    tag: "el-input",
    label: "邮箱",
    props: {
      placeholder: "请输入邮箱",
    },
  },
  {
    key: "phone",
    tag: "el-input",
    label: "手机号",
    props: {
      placeholder: "请输入手机号",
    },
  },
  {
    key: "status",
    tag: "el-select",
    label: "状态",
    defaultValue: "1",
    props: {
      placeholder: "请选择状态",
    },
    children: [
      {
        tag: "el-option",
        props: {
          label: "启用",
          value: "1",
        },
      },
      {
        tag: "el-option",
        props: {
          label: "禁用",
          value: "0",
        },
      },
    ],
  },
  // 删除头像字段配置
];

// 用户表单验证规则
const userFormRules = {
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
};

// 页面初始化
onMounted(() => {
  fetchUserList();
  fetchRoleList();
});

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true;
  try {
    const params: SysUser = {
      ...searchFormData,
      pageNum: pagination.page,
      pageSize: pagination.limit,
    };
    const res: any = await userApi.page(params);
    tableData.value = res.records;
    pagination.total = res.total;
  } catch (error) {
    console.error("获取用户列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const res: any = await roleApi.findAll();
    roleList.value = res;
  } catch (error) {
    console.error("获取角色列表失败:", error);
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  fetchUserList();
};

// 重置搜索
const handleReset = () => {
  searchFormRef.value?.resetForm();
  pagination.page = 1;
  fetchUserList();
};

// 分页变化
const handlePageChange = (val: any) => {
  if (Number.isInteger(val.page)) {
    pagination.page = val.page;
  }
  if (Number.isInteger(val.limit)) {
    pagination.limit = val.limit;
  }
  fetchUserList();
};

// 新增用户 (删除sex和avatar相关代码)
const handleAdd = () => {
  isEdit.value = false;
  dialogTitle.value = "新增用户";
  // 重置表单数据
  Object.assign(userFormData, {
    id: undefined,
    deptId: undefined,
    userName: "",
    nickName: "",
    userType: "00",
    email: "",
    phone: "",
    // 删除sex字段
    // 删除avatar字段
    password: "",
    status: "1",
    loginIp: "",
    loginDate: "",
  });
  dialogVisible.value = true;
};

// 编辑用户
const handleEdit = (row: any) => {
  isEdit.value = true;
  dialogTitle.value = "编辑用户";
  // 填充表单数据
  Object.assign(userFormData, {
    ...row,
    password: "", // 编辑时不显示原密码
  });
  dialogVisible.value = true;
};

// 保存用户
const handleSave = async () => {
  try {
    await userFormRef.value?.checkValidate();

    if (isEdit.value) {
      // 编辑
      const { password, ...updateData } = userFormData;
      await userApi.updateUser(updateData);
      ElMessage.success("更新成功");
      dialogVisible.value = false;
      fetchUserList();
    } else {
      // 新增
      await userApi.addUser(userFormData);
      ElMessage.success("新增成功");
      dialogVisible.value = false;
      fetchUserList();
    }
  } catch (error) {}
};

// 关闭对话框
const handleDialogClose = () => {
  userFormRef.value?.resetForm();
};

// 删除用户
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除用户"${row.userName}"吗？`, "确认删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await userApi.deleteUser(row.id);
        ElMessage.success("删除成功");
        fetchUserList();
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 分配角色
const handleAssignRoles = async (row: any) => {
  currentUserId.value = row.id;
  try {
    // 获取用户已有角色
    console.log(row.roles);
    // 需要回显row.roles的值
    const checkedKeys = row.roles.map((role: any) => role.id);
    nextTick(() => {
      selectedRoleIds.value = [];
      roleTreeRef.value!.setCheckedKeys(checkedKeys);
    });
    roleDialogVisible.value = true;
  } catch (error) {
    console.error("获取用户角色失败:", error);
    ElMessage.error("获取用户角色失败");
  }
};

// 保存角色分配
const handleSaveRoles = async () => {
  if (!currentUserId.value) return;

  try {
    const checkedKeys = roleTreeRef.value!.getCheckedKeys();
    await userApi.assignRoles(currentUserId.value, checkedKeys);
    ElMessage.success("角色分配成功");
    fetchUserList();
    roleDialogVisible.value = false;
  } catch (error) {
    console.error("角色分配失败:", error);
    ElMessage.error("角色分配失败");
  }
};
</script>

<style scoped lang="scss">
.user-management {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.dialog-footer {
  text-align: right;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  min-height: 24px;
}
</style>
